/**
 * 数据库初始化脚本
 * 创建项目相关集合和索引
 */

/**
 * 项目数据库初始化
 */
async function initProjectDB(db) {
  console.log('======== 开始初始化项目数据库 ========');

  // 1. 创建项目集合
  console.log('创建项目集合...');
  try {
    await db.createCollection('projects', {
      validator: {
        $jsonSchema: {
          bsonType: 'object',
          required: ['model', 'projectType', 'customerName', 'startDate', 'deadline'],
          properties: {
            // 项目基本字段定义
            model: { bsonType: 'string' },
            projectType: { bsonType: 'string' },
            customerName: { bsonType: 'string' },
            description: { bsonType: 'string' },
            
            // 状态字段
            level1: { bsonType: 'int', minimum: 1 },
            level2: { bsonType: 'string' },
            level3: { bsonType: 'string' },
            level4: { bsonType: 'string' },
            
            // 分支相关字段
            masterBranchId: { bsonType: 'string' },
            
            // 时间字段
            startDate: { bsonType: 'int' },
            deadline: { bsonType: 'int' },
            createTime: { bsonType: 'int' },
            updateTime: { bsonType: 'int' },
            
            // 共享字段
            sharedFields: {
              bsonType: 'object',
              properties: {
                description: { bsonType: 'string' },
                startDate: { bsonType: 'int' },
                deadline: { bsonType: 'int' },
                priority: { bsonType: 'string' },
                developmentManager: { bsonType: 'string' },
                businessManager: { bsonType: 'string' }
              }
            }
          }
        }
      }
    });
    console.log('项目集合创建成功');
  } catch (err) {
    if (err.codeName === 'NamespaceExists') {
      console.log('项目集合已存在，跳过创建');
    } else {
      console.error('创建项目集合失败:', err);
      throw err;
    }
  }

  // 2. 创建项目分支集合
  console.log('创建项目分支集合...');
  try {
    await db.createCollection('project_branches', {
      validator: {
        $jsonSchema: {
          bsonType: 'object',
          required: ['projectId', 'name', 'createTime'],
          properties: {
            // 关联信息
            projectId: { bsonType: 'string' },
            name: { bsonType: 'string' },
            parentId: { bsonType: 'string' },
            
            // 分支标记
            isMaster: { bsonType: 'bool' },
            isActive: { bsonType: 'bool' },
            
            // 状态字段
            level1: { bsonType: 'int', minimum: 1 },
            level2: { bsonType: 'string' },
            level3: { bsonType: 'string' },
            level4: { bsonType: 'string' },
            statusDesc: { bsonType: 'string' },
            completionPercentage: { bsonType: 'int', minimum: 0, maximum: 100 },
            
            // 源节点信息
            sourceNodeId: { bsonType: 'string' },
            sourceNodeTime: { bsonType: 'int' },
            sourceNodeStatus: {
              bsonType: 'object',
              properties: {
                level1: { bsonType: 'int' },
                level2: { bsonType: 'string' },
                level3: { bsonType: 'string' },
                level4: { bsonType: 'string' }
              }
            },
            
            // 时间信息
            createTime: { bsonType: 'int' },
            updateTime: { bsonType: 'int' },
            stateTime: { bsonType: 'int' },
            
            // 创建者信息
            createdBy: { bsonType: 'string' },
            createdByName: { bsonType: 'string' }
          }
        }
      }
    });
    console.log('项目分支集合创建成功');
  } catch (err) {
    if (err.codeName === 'NamespaceExists') {
      console.log('项目分支集合已存在，跳过创建');
    } else {
      console.error('创建项目分支集合失败:', err);
      throw err;
    }
  }

  // 3. 创建项目状态历史集合
  console.log('创建项目状态历史集合...');
  try {
    await db.createCollection('project_state_history', {
      validator: {
        $jsonSchema: {
          bsonType: 'object',
          required: ['projectId', 'branchId', 'fromState', 'toState', 'createdTime'],
          properties: {
            // 关联信息
            projectId: { bsonType: 'string' },
            branchId: { bsonType: 'string' },
            
            // 状态信息
            fromState: {
              bsonType: 'object',
              required: ['level1', 'level2'],
              properties: {
                level1: { bsonType: 'int' },
                level2: { bsonType: 'string' },
                level3: { bsonType: 'string' },
                level4: { bsonType: 'string' }
              }
            },
            toState: {
              bsonType: 'object',
              required: ['level1', 'level2'],
              properties: {
                level1: { bsonType: 'int' },
                level2: { bsonType: 'string' },
                level3: { bsonType: 'string' },
                level4: { bsonType: 'string' }
              }
            },
            eventType: { bsonType: 'string' },
            
            // 状态细节
            fromLevel1: { bsonType: 'int' },
            fromLevel2: { bsonType: 'string' },
            fromLevel3: { bsonType: 'string' },
            fromLevel4: { bsonType: 'string' },
            
            toLevel1: { bsonType: 'int' },
            toLevel2: { bsonType: 'string' },
            toLevel3: { bsonType: 'string' },
            toLevel4: { bsonType: 'string' },
            
            // 备注信息
            comment: { bsonType: 'string' },
            attachments: { 
              bsonType: 'array',
              items: { bsonType: 'string' }
            },
            
            // 创建信息
            createdBy: { bsonType: 'string' },
            createdByName: { bsonType: 'string' },
            createdTime: { bsonType: 'int' }
          }
        }
      }
    });
    console.log('项目状态历史集合创建成功');
  } catch (err) {
    if (err.codeName === 'NamespaceExists') {
      console.log('项目状态历史集合已存在，跳过创建');
    } else {
      console.error('创建项目状态历史集合失败:', err);
      throw err;
    }
  }

  // 4. 创建索引
  console.log('创建索引...');
  
  try {
    // 项目集合索引
    await db.collection('projects').createIndex({ model: 1 });
    await db.collection('projects').createIndex({ projectType: 1 });
    await db.collection('projects').createIndex({ customerName: 1 });
    await db.collection('projects').createIndex({ level1: 1 });
    await db.collection('projects').createIndex({ masterBranchId: 1 });
    await db.collection('projects').createIndex({ createTime: -1 });
    await db.collection('projects').createIndex({ deadline: 1 });
    await db.collection('projects').createIndex({ 'sharedFields.priority': 1 });
    await db.collection('projects').createIndex({ 'sharedFields.developmentManager': 1 });
    await db.collection('projects').createIndex({ 'sharedFields.businessManager': 1 });
    
    // 项目分支集合索引
    await db.collection('project_branches').createIndex({ projectId: 1 });
    await db.collection('project_branches').createIndex({ parentId: 1 });
    await db.collection('project_branches').createIndex({ projectId: 1, isMaster: 1 });
    await db.collection('project_branches').createIndex({ createdBy: 1 });
    await db.collection('project_branches').createIndex({ level1: 1 });
    await db.collection('project_branches').createIndex({ createTime: -1 });
    await db.collection('project_branches').createIndex({ updateTime: -1 });
    await db.collection('project_branches').createIndex({ completionPercentage: 1 });
    await db.collection('project_branches').createIndex({ isActive: 1 });
    
    // 项目状态历史集合索引
    await db.collection('project_state_history').createIndex({ projectId: 1, createdTime: -1 });
    await db.collection('project_state_history').createIndex({ branchId: 1, createdTime: -1 });
    await db.collection('project_state_history').createIndex({ fromLevel1: 1, toLevel1: 1 });
    await db.collection('project_state_history').createIndex({ createdBy: 1 });
    await db.collection('project_state_history').createIndex({ eventType: 1 });
    await db.collection('project_state_history').createIndex({ 'fromState.level1': 1, 'toState.level1': 1 });
    
    console.log('索引创建成功');
  } catch (err) {
    console.error('创建索引失败:', err);
    throw err;
  }
  
  console.log('======== 项目数据库初始化完成 ========');
}

/**
 * 主函数
 */
async function main() {
  const { MongoClient } = require('mongodb');
  
  const uri = process.env.MONGODB_URI || 'mongodb://localhost:27017';
  const dbName = process.env.DB_NAME || 'abs_oa';
  
  console.log('连接到数据库...');
  
  let client;
  
  try {
    client = new MongoClient(uri);
    await client.connect();
    console.log('数据库连接成功');
    
    const db = client.db(dbName);
    
    // 初始化项目数据库
    await initProjectDB(db);
    
    console.log('数据库初始化完成');
  } catch (err) {
    console.error('数据库初始化失败:', err);
    process.exit(1);
  } finally {
    if (client) {
      await client.close();
      console.log('数据库连接已关闭');
    }
  }
}

// 执行主函数
main().catch(console.error);

module.exports = {
  initProjectDB
}; 